package com.yafeng.shiro;

import com.yafeng.exception.CustomException;
import com.yafeng.utils.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Slf4j
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

    /**
     * 想干一件事
     *    就是通过传入数据的类型  来选择使用哪一个Realm
     * @param auto
     * @return
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken auto) {

        // 判断getRealms()是否返回为空
        assertRealmsConfigured();
        // 强制转换回自定义的CustomizedToken
        UserToken userToken = null;

        String loginType=null;
        // 登录类型

        try {
            userToken = (UserToken) auto;
            loginType = userToken.getLoginType();
        } catch (Exception e) {

            loginType = "MyRealm";
        }

        // 所有Realm
        Collection<Realm> realms = getRealms();
        // 登录类型对应的所有Realm
        List<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {

            if (realm.getName().contains(loginType)) {
                typeRealms.add(realm);
            }
        }

        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1){
            System.out.println("doSingleRealmAuthentication() execute ");
            if(userToken==null){
                return doSingleRealmAuthentication(typeRealms.get(0), auto);
            }else {
                return doSingleRealmAuthentication(typeRealms.get(0), userToken);
            }
        }
        else{
            System.out.println("doMultiRealmAuthentication() execute ");
            return doMultiRealmAuthentication(typeRealms, userToken);
        }

    }

}
